﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Windows.Data;

namespace be.metanous.mvvm.converters
{
    public class CollectionViewSourceConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {

            try
            {
                var list = CollectionViewSource.GetDefaultView(value);
                if (list != null && parameter is string && !string.IsNullOrEmpty(parameter as string))
                {

                    var parameterlist = (parameter as string).Split('|');

                    if (parameterlist.Length % 2 != 0) return value;

                    for (int i = 0; i < parameterlist.Length - 1; i += 2 )
                    {

                        var direction = "asc".Equals(parameterlist[i + 1].ToLower())
                                            ? ListSortDirection.Ascending
                                            : ListSortDirection.Descending;

                        list.SortDescriptions.Add(new SortDescription(parameterlist[i], direction));
                    }


                        
                }


                return list;
            }
            catch (Exception) { }




            return value;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return null;
        }
    }
}
